package com.ybu.service.impl;

import com.ybu.common.*;
import com.ybu.mapper.UserMapper;
import com.ybu.pojo.dto.RegisterDTO;
import com.ybu.pojo.dto.UserLoginDTO;
import com.ybu.pojo.entity.User;
import com.ybu.pojo.vo.UserLoginVO;
import com.ybu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;


@Service //业务层
@Slf4j
@Transactional //事务
public class UserServiceImpl implements UserService {
    //注入持久层
    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(RegisterDTO registerDTO) {
        //判断密码与重复密码是否一致
        if (!registerDTO.getPassword().equals(registerDTO.getRePassword())) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "两次输入密码不一致");
        }
            //生成salt
            String salt = UUID.randomUUID().toString().replace("-", "");
            // 对密码进行加密
            String  password = MD5Utils.enctype(registerDTO.getPassword(), salt, Constants.HASH_TIME);
            log.debug("密码加密后：{}", password);
            log.debug("salt：{}", salt);

        //封装user
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        //使用加密后的密码
        user.setPassword(password);
        user.setSalt(salt);
        user.setIsDelete(Constants.IS_NOT_DELETE);
        user.setCreatedUser(registerDTO.getUsername());
        //调用持久层进行新增用户
        int result = userMapper.insert(user);
        if (result != 1) {
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "注册用户失败");
        }
    }

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO){
        //根据用户名查询用户
         User user = userMapper.getByName(userLoginDTO.getUsername());
         if (user == null || userLoginDTO.getUsername().isEmpty()){
             throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该用户未找到");
         }
        //判断是否被锁定
        if (user.getIsDelete()== 1){
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"该账号被锁定");

        }
        //判断密码
        //将登录密码加密
        //log.debug("user.password:{}",userLoginDTO.getPassword());
        String password = MD5Utils.enctype(userLoginDTO.getPassword(), user.getSalt(), Constants.HASH_TIME);
        //log.debug("user.password:{}",userLoginDTO.getPassword());
        //log.debug("password:{}",password);
        if(!user.getPassword().equals(password) ){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"密码错误");
        }


        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setUsername(user.getUsername());

        String token = JwtUtils.generateToken(userLoginVO);
        userLoginVO.setToken(token);
        return userLoginVO;
    }
}